package com.kyxx.topics;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;

//import com.example.playerdemo.handler.CrashHandler;
//import com.kyxx.topics.utils.ToastUtils;
//import com.lecloud.config.LeCloudPlayerConfig;
//import com.letv.proxy.LeCloudProxy;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.kyxx.topics.bean.AppModel;
import com.kyxx.topics.utils.Constants;
import com.kyxx.topics.utils.SettingUtils;
import com.kyxx.topics.utils.StringUtil;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.view.CropImageView;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheEntity;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.cookie.store.PersistentCookieStore;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.pgyersdk.crash.PgyCrashManager;
import com.uuch.adlibrary.utils.DisplayUtil;

import java.util.List;
import java.util.Set;
import java.util.Stack;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

public class BaseApp extends Application {

    /**
     * 存储的sharePerfence
     */
    public static final String config = "config";//存储的sharePerfence
    public static final String IS_INTRO = "is_intro";//当前的是否已经进行过指引
    public static final String VERSION = "version";//当前应用中存储的版本号

    // ===========常量==========
    public static final String TAG = "BaseApp";
    public static final String FILE_DIR = "heer_dir";

    private static Context context;
    private static Stack<Activity> activityStack;
    private static BaseApp instance;
    private static AppModel model;

    public BaseApp() {
    }

    public synchronized static BaseApp getInstance() {
        if (null == instance) {
            instance = new BaseApp();
        }
        return instance;
    }

    private void initModel() {
        /* 初始化用户Model */
        model = AppModel.init(this);
    }

    /**
     * 获取用户信息
     */
    public static AppModel getModel() {
        if (model == null) {
            Log.e("application", "appmodel is null");
        }
        return model;
    }

    /**
     * 验证用户是否登录
     */
    public static boolean validateUserLogin() {
        if (StringUtil.isEmpty(model.getMobile())) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 打开Activity
     */
    public void addActivity(Activity activity) {
        if (activityStack == null) {
            activityStack = new Stack<Activity>();
        }
        activityStack.add(activity);

        Log.d(TAG, "-----------------------------------");
        for (Activity temp : activityStack) {
            Log.d(TAG, "类名:" + temp.toString() + "地址：" + temp);
        }
        Log.d(TAG, "===================================");
    }

    /**
     * 获取当前Activity
     */
    public Activity currentActivity() {
        Activity activity = activityStack.lastElement();
        return activity;
    }

    /**
     * 关闭Activity
     */
    public void finishActivity() {
        Activity activity = activityStack.lastElement();
        finishActivity(activity);
    }

    /**
     * 关闭指定Activity
     */
    public void finishActivity(Activity activity) {
        if (activity != null) {
            activityStack.remove(activity);
            activity.finish();
            activity = null;
        }
    }

    /**
     * 关闭所有的Activity
     */
    public void finishAllActivity() {
        for (int i = 0, size = activityStack.size(); i < size; i++) {
            if (null != activityStack.get(i)) {
                activityStack.get(i).finish();
            }
        }
        activityStack.clear();
    }

    /**
     * 当前界面恢复时的操作
     */
    public void resumeActivity(Activity activity) {
        if (activityStack.lastElement() == activity) {
            return;
        }
        activityStack.remove(activity);
        activityStack.push(activity);

        Log.d(TAG, "最后一个参数:" + activityStack.lastElement());
    }

    public void exit() {
        finishAllActivity();
        System.exit(0);
    }

    public void onLowMemory() {
        super.onLowMemory();
        System.gc();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "[ExampleApplication] onCreate");
        instance = this;
        context = getApplicationContext();
        initDisplayOpinion();
        Fresco.initialize(this);
        initImageLoader();
        initModel();//初始化 数据
        JPushInterface.setDebugMode(false);
        JPushInterface.init(this);
        if (!TextUtils.isEmpty(BaseApp.getModel().getId())) {
            JPushInterface.setAlias(context, BaseApp.getModel().getId(), new TagAliasCallback() {
                @Override
                public void gotResult(int i, String s, Set<String> set) {
                    Log.e("别名", BaseApp.getModel().getId());
                }
            });
        }
        PgyCrashManager.register(this);
        //必须调用初始化
        OkGo.init(this);
        initOkGo();
        initImagePicker();
    }

    private void initImagePicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new com.kyxx.topics.utils.ImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);                      //显示拍照按钮
        imagePicker.setCrop(false);                           //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true);                   //是否按矩形区域保存
        imagePicker.setSelectLimit(9);                        //选中数量限制
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);                       //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);                      //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);                         //保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);                         //保存文件的高度。单位像素
    }

    /**
     * 获取全局Context
     */
    public static Context getContext() {
        return context;
    }

    /**
     * 初始化ImageLoader
     */
    protected void initImageLoader() {
        //初始化ImageLoader
        ImageLoaderConfiguration.Builder config = new ImageLoaderConfiguration.Builder(this);
        config.threadPriority(Thread.NORM_PRIORITY - 2);
        config.denyCacheImageMultipleSizesInMemory();
        config.diskCacheFileNameGenerator(new Md5FileNameGenerator());
        config.diskCacheSize(50 * 1024 * 1024);
        config.tasksProcessingOrder(QueueProcessingType.LIFO);
//        config.writeDebugLogs();

        ImageLoader.getInstance().init(config.build());
    }

    public static String getProcessName(Context cxt, int pid) {
        ActivityManager am = (ActivityManager) cxt.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningApps = am.getRunningAppProcesses();
        if (runningApps != null) {
            for (ActivityManager.RunningAppProcessInfo procInfo : runningApps) {
                if (procInfo.pid == pid) {
                    return procInfo.processName;
                }
            }
        }
        return null;
    }

    private void initOkGo() {
        //以下设置的所有参数是全局参数,同样的参数可以在请求的时候再设置一遍,那么对于该请求来讲,请求中的参数会覆盖全局参数
        //好处是全局参数统一,特定请求可以特别定制参数
        try {
            //以下都不是必须的，根据需要自行选择,一般来说只需要 debug,缓存相关,cookie相关的 就可以了
            OkGo.getInstance()

                    //打开该调试开关,控制台会使用 红色error 级别打印log,并不是错误,是为了显眼,不需要就不要加入该行
                    .debug("OkGo")
                    .setRetryCount(3)
                    //如果使用默认的 60秒,以下三行也不需要传
                    .setConnectTimeout(Constants.TIME_OUT)  //全局的连接超时时间
                    .setReadTimeOut(Constants.TIME_OUT)     //全局的读取超时时间
                    .setWriteTimeOut(Constants.TIME_OUT)    //全局的写入超时时间

                    //可以全局统一设置缓存模式,默认是不使用缓存,可以不传,具体其他模式看 github 介绍 https://github.com/jeasonlzy/
                    .setCacheMode(CacheMode.NO_CACHE)

                    //可以全局统一设置缓存时间,默认永不过期,具体使用方法看 github 介绍
                    .setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE)

                    //如果不想让框架管理cookie,以下不需要
//                .setCookieStore(new MemoryCookieStore())                //cookie使用内存缓存（app退出后，cookie消失）
                    .setCookieStore(new PersistentCookieStore());       //cookie持久化存储，如果cookie不过期，则一直有效

            //可以设置https的证书,以下几种方案根据需要自己设置,不需要不用设置
//                    .setCertificates()                                  //方法一：信任所有证书
//                    .setCertificates(getAssets().open("srca.cer"))      //方法二：也可以自己设置https证书
//                    .setCertificates(getAssets().open("aaaa.bks"), "123456", getAssets().open("srca.cer"))//方法三：传入bks证书,密码,和cer证书,支持双向加密

            //可以添加全局拦截器,不会用的千万不要传,错误写法直接导致任何回调不执行
//                .addInterceptor(new Interceptor() {
//                    @Override
//                    public Response intercept(Chain chain) throws IOException {
//                        return chain.proceed(chain.request());
//                    }
//                })

            //这两行同上,不需要就不要传
//                    .addCommonHeaders(headers)                                         //设置全局公共头
//                    .addCommonParams(params);                                          //设置全局公共参数
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initDisplayOpinion() {
        DisplayMetrics dm = getResources().getDisplayMetrics();
        DisplayUtil.density = dm.density;
        DisplayUtil.densityDPI = dm.densityDpi;
        DisplayUtil.screenWidthPx = dm.widthPixels;
        DisplayUtil.screenhightPx = dm.heightPixels;
        DisplayUtil.screenWidthDip = DisplayUtil.px2dip(getApplicationContext(), dm.widthPixels);
        DisplayUtil.screenHightDip = DisplayUtil.px2dip(getApplicationContext(), dm.heightPixels);
    }
}